<template>
  <div class="login">
    <div class="animation-bg-bubbles"><i /><i /><i /><i /><i /><i /><i /><i /><i /><i /></div>
    <el-form
      ref="loginForm"
      :model="loginForm"
      :rules="loginRules"
      class="login-form"
      auto-complete="off"
      label-position="left"
    >
      <div class="title-container">
        <h3 class="title">
          {{ $t('login.title') }}
        </h3>
        <lang-select class="set-language" />
      </div>

      <el-form-item prop="username">
        <el-input
          ref="username"
          v-model="loginForm.username"
          :placeholder="$t('login.username')"
          name="username"
          type="text"
          auto-complete="off"
        >
          <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" />
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          :key="passwordType"
          ref="password"
          v-model="loginForm.password"
          :type="passwordType"
          :placeholder="$t('login.password')"
          name="password"
          auto-complete="off"
          placeholder="密码"
          @keyup.enter.native="handleLogin"
        >
          <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" />
        </el-input>
        <span class="show-pwd" @click="showPwd">
          <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" class="el-input__icon input-icon" />
        </span>
      </el-form-item>

      <el-form-item prop="code">
        <el-input
          v-model="loginForm.code"
          auto-complete="off"
          :placeholder="$t('login.validCode')"
          style="width: 60%"
          @keyup.enter.native="handleLogin"
        >
          <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon" />
        </el-input>
        <div class="login-code">
          <img :src="validCodeUrl" @click="getValidCode" />
        </div>
      </el-form-item>

      <el-form-item>
        <div style="display: flex; justify-content: space-between">
          <el-checkbox v-model="loginForm.rememberMe">{{ $t('login.rememberMe') }}</el-checkbox>
          <el-button type="text">{{ $t('login.registeredUser') }}</el-button>
          <el-button type="text">{{ $t('login.forgetPassword') }}</el-button>
          <el-button class="thirdparty-button" type="primary" @click="showDialog = true">
            {{ $t('login.thirdparty') }}
          </el-button>
        </div>
      </el-form-item>

      <el-form-item>
        <el-button :loading="loading" type="primary" style="width: 100%" @click.native.prevent="handleLogin">
          {{ $t('login.logIn') }}
        </el-button>
      </el-form-item>
    </el-form>

    <el-dialog :title="$t('login.thirdparty')" :visible.sync="showDialog">
      {{ $t('login.thirdpartyTips') }}
      <br />
      <br />
      <br />
      <social-sign />
    </el-dialog>
  </div>
</template>

<script>
import { getValidCodeImg } from '@/api/login';
import Cookies from 'js-cookie';
import { encrypt, decrypt } from '@/utils/jsencrypt';
import LangSelect from '@/components/LangSelect';
import SocialSign from './components/SocialSignin';
// import Config from '../../settings'

export default {
  name: 'Login',
  components: { LangSelect, SocialSign },
  data() {
    const notEmptyMsg = this.$t('verify.notEmpty');

    return {
      validCodeUrl: '',
      loginForm: {
        username: '',
        password: '',
        rememberMe: false,
        code: '',
        uuid: '',
      },
      loginRules: {
        username: [{ required: true, trigger: 'blur', message: this.$t('login.username') + notEmptyMsg }],
        password: [{ required: true, trigger: 'blur', message: this.$t('login.password') + notEmptyMsg }],
        code: [{ required: true, trigger: 'change', message: this.$t('login.validCode') + notEmptyMsg }],
      },
      passwordType: 'password',
      capsTooltip: false,
      loading: false,
      // 验证码开关
      captchaOnOff: true,
      // 注册开关
      register: false,
      showDialog: false,
      redirect: undefined,
    };
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true,
    },
  },
  created() {
    this.getValidCode();
    this.getCookie();
  },
  mounted() {
    if (this.loginForm.username === '') {
      this.$refs.username.focus();
    } else if (this.loginForm.password === '') {
      this.$refs.password.focus();
    } else if (this.loginForm.validCode === '') {
      this.$refs.validCode.focus();
    }
  },
  methods: {
    checkCapslock({ shiftKey, key } = {}) {
      if (key && key.length === 1) {
        if ((shiftKey && key >= 'a' && key <= 'z') || (!shiftKey && key >= 'A' && key <= 'Z')) {
          this.capsTooltip = true;
        } else {
          this.capsTooltip = false;
        }
      }
      if (key === 'CapsLock' && this.capsTooltip === true) {
        this.capsTooltip = false;
      }
    },
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = '';
      } else {
        this.passwordType = 'password';
      }
      this.$nextTick(() => {
        this.$refs.password.focus();
      });
    },
    getValidCode() {
      getValidCodeImg().then((resultDTO) => {
        this.captchaOnOff = resultDTO.data?.captchaOnOff === undefined ? true : resultDTO.data?.captchaOnOff;
        if (this.captchaOnOff) {
          this.validCodeUrl = 'data:image/gif;base64,' + resultDTO.data?.img;
          this.loginForm.uuid = resultDTO.data?.uuid;
        }
      });
    },
    getCookie() {
      const username = Cookies.get('username');
      let password = Cookies.get('password');
      const rememberMe = Cookies.get('rememberMe');
      password = password === undefined ? this.loginForm.password : decrypt(password);
      this.loginForm = {
        username: username === undefined ? this.loginForm.username : username,
        password: password,
        rememberMe: rememberMe === undefined ? false : Boolean(rememberMe),
        code: '',
      };
    },
    handleLogin() {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          if (this.loginForm.rememberMe) {
            Cookies.set('username', this.loginForm.username, { expires: 30 });
            Cookies.set('password', encrypt(this.loginForm.password), { expires: 30 });
            Cookies.set('rememberMe', this.loginForm.rememberMe, { expires: 30 });
          } else {
            Cookies.remove('username');
            Cookies.remove('password');
            Cookies.remove('rememberMe');
          }
          this.$store
            .dispatch('Login', this.loginForm)
            .then(() => {
              this.$router.push({ path: this.redirect || '/' }).catch(() => {});
            })
            .catch(() => {
              this.loading = false;
              if (this.captchaOnOff) {
                this.getValidCode();
              }
            });
        }
      });
      // afterQRScan() {
      //   if (e.key === 'x-admin-oauth-code') {
      //     const code = getQueryObject(e.newValue)
      //     const codeMap = {
      //       wechat: 'code',
      //       tencent: 'code'
      //     }
      //     const type = codeMap[this.auth_type]
      //     const codeName = code[type]
      //     if (codeName) {
      //       this.$store.dispatch('LoginByThirdparty', codeName).then(() => {
      //         this.$router.push({ path: this.redirect || '/' })
      //       })
      //     } else {
      //       alert('第三方登录失败')
      //     }
      //   }
      // }
    },
  },
};
</script>

<style rel="stylesheet/scss" lang="scss">
$bg: #283443;
$cursor: #fff;
$dark_gray: #889aa4;
$light_gray: #707070;
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background: #0f203a;
  background-image: url('../../assets/images/login-bg.svg');
  background-size: cover;

  .input-prefix-icon {
    height: 38px;
    width: 13px;
    margin-left: 5px;
  }

  .login-form {
    border-radius: 10px;
    background: #ffffff;
    width: 390px;
    padding: 25px 25px 5px 25px;
  }

  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;

    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .title-container {
    position: relative;

    .title {
      font-size: 26px;
      font-family: Helvetica Neue, Helvetica, Tahoma, Arial, sans-serif;
      color: $light_gray;
      margin: 0px auto 30px auto;
      text-align: center;
      font-weight: bold;
    }

    .set-language {
      color: $light_gray;
      position: absolute;
      top: 3px;
      font-size: 18px;
      right: 0px;
      cursor: pointer;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 0px;
    font-size: 16px;
    height: 38px;
    line-height: 38px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
  .login-code {
    width: 33%;
    display: inline-block;
    height: 38px;
    float: right;
    img {
      width: 100%;
      height: 100%;
      border-radius: 4px;
      cursor: pointer;
      vertical-align: middle;
    }
  }

  @media only screen and (max-width: 470px) {
    .thirdparty-button {
      display: none;
    }
  }
}
</style>
